<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="C++_emplace_back"><meta name="keywords" content="C++"><meta name="author" content="LiYang"><meta name="copyright" content="LiYang"><title>C++_emplace_back | 一条鲤鱼</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="一条鲤鱼" type="application/atom+xml">
</head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="Toggle article">Toggle site</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">Catalog</div><div class="sidebar-toc__progress"><span class="progress-notice">You've read</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A6%82%E8%BF%B0"><span class="toc-number">1.</span> <span class="toc-text">概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8"><span class="toc-number">2.</span> <span class="toc-text">使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%AE%80%E5%8D%95%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-number">2.1.</span> <span class="toc-text">简单的使用</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8E%9F%E7%90%86"><span class="toc-number">3.</span> <span class="toc-text">原理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%9B%E4%B8%80%E6%AD%A5%E8%AE%A8%E8%AE%BA"><span class="toc-number">4.</span> <span class="toc-text">进一步讨论</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">LiYang</div><div class="author-info__description text-center"></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">Articles</span><span class="pull-right">13</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">Tags</span><span class="pull-right">6</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">Categories</span><span class="pull-right">7</span></a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">一条鲤鱼</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"></span></div><div id="post-info"><div id="post-title">C++_emplace_back</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2021-10-09</time><span class="post-meta__separator">|</span><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">编程语言</a><i class="fa fa-angle-right" aria-hidden="true"></i><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/C/">C++</a></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>参考：<a target="_blank" rel="noopener" href="https://www.jianshu.com/p/c0cbd9dbf772">https://www.jianshu.com/p/c0cbd9dbf772</a></p>
<h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>我们在对STL容器进行插入操作时，常会使用<code>insert</code>或<code>push_back</code>。C++11提出了更高效的插入方法：<code>emplace</code>。</p>
<p>本文将介绍C++11新特性中<code>emplace</code>的使用与原理。</p>
<hr>
<h2 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h2><p>首先，介绍下<code>emplace</code>相对应的函数：</p>
<ul>
<li>对于vector，emplace()可以替换insert()，emplace_back()可以替换push_back()。</li>
<li>对于set，emplace()可以替换insert()。</li>
<li>对于map，emplace()可以替换insert()。</li>
</ul>
<h3 id="简单的使用"><a href="#简单的使用" class="headerlink" title="简单的使用"></a>简单的使用</h3><ul>
<li><p>以vector的emplace_back()为例：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;vector&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">Student</span> &#123;</span></span><br><span class="line">    string name;</span><br><span class="line">    <span class="keyword">int</span> age;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">Student</span>(string&amp;&amp; n, <span class="keyword">int</span> a)</span><br><span class="line">        :<span class="built_in">name</span>(std::<span class="built_in">move</span>(n)), <span class="built_in">age</span>(a)</span><br><span class="line">    &#123;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">//基本数据类型的插入</span></span><br><span class="line">    vector&lt;<span class="keyword">int</span>&gt; arr;</span><br><span class="line">    arr.<span class="built_in">push_back</span>(<span class="number">1</span>);</span><br><span class="line">    arr.<span class="built_in">emplace_back</span>(<span class="number">1</span>);</span><br><span class="line">  </span><br><span class="line">    <span class="comment">//自定义类型的插入</span></span><br><span class="line">    vector&lt;Student&gt; classes;</span><br><span class="line">    classes.<span class="built_in">emplace_back</span>(<span class="string">&quot;xiaohong&quot;</span>, <span class="number">24</span>); <span class="comment">//无需先创建对象</span></span><br><span class="line">    classes.<span class="built_in">push_back</span>(<span class="built_in">Student</span>(<span class="string">&quot;xiaoming&quot;</span>, <span class="number">23</span>)); <span class="comment">//需先创建对象</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
<li><p>我们注意到，使用emplace_back向vector增添元素时，无须先创建对象，而使用push_back()向vector中增添元素时，需要先创建对象，再添加到数组中。这就涉及到emplace_back()的工作机制了。</p>
</li>
</ul>
<h2 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h2><ul>
<li><p><code>push_back()</code>：先向容器尾部添加一个右值元素(临时对象)，然后调用<strong>构造函数</strong>构造出这个临时对象，最后调用<strong>移动构造函数</strong>将这个临时对象放入容器中并释放这个临时对象。<br> <strong>注：最后调用的不是拷贝构造函数，而是移动构造函数。</strong>因为需要释放临时对象，所以通过<code>std::move</code>进行移动构造，可以避免不必要的拷贝操作</p>
</li>
<li><p><code>emplace_back()</code>：在容器尾部添加一个元素，调用<strong>构造函数</strong>原地构造，不需要触发拷贝构造和移动构造。因此比<code>push_back()</code>更加高效。</p>
</li>
<li><p>通过下面程序我们可以验证一下：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;vector&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> std;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">struct</span> <span class="title">Student</span> &#123;</span></span><br><span class="line">    string name;</span><br><span class="line">    <span class="keyword">int</span> age;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">Student</span>(string&amp;&amp; n, <span class="keyword">int</span> a)</span><br><span class="line">        :<span class="built_in">name</span>(std::<span class="built_in">move</span>(n)), <span class="built_in">age</span>(a)</span><br><span class="line">    &#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;构造&quot;</span> &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">Student</span>(<span class="keyword">const</span> Student&amp; s)</span><br><span class="line">        : <span class="built_in">name</span>(std::<span class="built_in">move</span>(s.name)), <span class="built_in">age</span>(s.age)</span><br><span class="line">    &#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;拷贝构造&quot;</span> &lt;&lt; endl;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">Student</span>(Student&amp;&amp; s)</span><br><span class="line">        :<span class="built_in">name</span>(std::<span class="built_in">move</span>(s.name)), <span class="built_in">age</span>(s.age)</span><br><span class="line">    &#123;</span><br><span class="line">        cout &lt;&lt; <span class="string">&quot;移动构造&quot;</span> &lt;&lt; endl;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    Student&amp; <span class="keyword">operator</span>=(<span class="keyword">const</span> Student&amp; s);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    vector&lt;Student&gt; classes_one;</span><br><span class="line">    vector&lt;Student&gt; classes_two;</span><br><span class="line"></span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;emplace_back:&quot;</span> &lt;&lt; endl;</span><br><span class="line">    classes_one.<span class="built_in">emplace_back</span>(<span class="string">&quot;xiaohong&quot;</span>, <span class="number">24</span>);</span><br><span class="line"></span><br><span class="line">    cout &lt;&lt; <span class="string">&quot;push_back:&quot;</span> &lt;&lt; endl;</span><br><span class="line">    classes_two.<span class="built_in">push_back</span>(<span class="built_in">Student</span>(<span class="string">&quot;xiaoming&quot;</span>, <span class="number">23</span>));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>执行结果：</p>
</li>
</ul>
<p><img src="/2021/10/09/C-emplace-back/result.jpg" alt="result"></p>
<h2 id="进一步讨论"><a href="#进一步讨论" class="headerlink" title="进一步讨论"></a>进一步讨论</h2><p>看了上文的示例代码，可能会有人问，为什么要分成两个容器分开插入来查看结果呢？因为一起插入时，会触发未知的<strong>拷贝构造</strong>操作，以及多次进行<code>emplace_back()</code>或<code>push_back()</code>操作时，也会触发<strong>拷贝构造</strong>操作。</p>
<p>这些拷贝构造操作是什么呢？这和vector的原理有关。当多次插入操作导致vector已满时，就要分配一块更大的内存(比原始大小多50%)，将原始数据复制过来并释放之前的内存。原始数据的复制就是这些<strong>拷贝构造</strong>操作。</p>
<p>进行多次插入，查看运行结果：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    vector&lt;Student&gt; classes;</span><br><span class="line"></span><br><span class="line">    classes.<span class="built_in">emplace_back</span>(<span class="string">&quot;xiaohong&quot;</span>, <span class="number">24</span>);</span><br><span class="line">    classes.<span class="built_in">emplace_back</span>(<span class="string">&quot;xiaohong&quot;</span>, <span class="number">24</span>);</span><br><span class="line">    classes.<span class="built_in">emplace_back</span>(<span class="string">&quot;xiaohong&quot;</span>, <span class="number">24</span>);</span><br><span class="line">    classes.<span class="built_in">emplace_back</span>(<span class="string">&quot;xiaohong&quot;</span>, <span class="number">24</span>);</span><br><span class="line">    classes.<span class="built_in">emplace_back</span>(<span class="string">&quot;xiaohong&quot;</span>, <span class="number">24</span>);</span><br><span class="line">    classes.<span class="built_in">emplace_back</span>(<span class="string">&quot;xiaohong&quot;</span>, <span class="number">24</span>);</span><br><span class="line">    classes.<span class="built_in">emplace_back</span>(<span class="string">&quot;xiaohong&quot;</span>, <span class="number">24</span>);</span><br><span class="line">    classes.<span class="built_in">emplace_back</span>(<span class="string">&quot;xiaohong&quot;</span>, <span class="number">24</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>结果如下，上图打印的“拷贝构造”即vector满时，需要分配更大的内存并复制原始数据而产生的。并且每次分配更大内存时，都比原始大小多50%，即1-&gt;2-&gt;3-&gt;4-&gt;6…</p>
<p><img src="/2021/10/09/C-emplace-back/result2.jpg" alt="result2"></p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">LiYang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://example.com/2021/10/09/C-emplace-back/">http://example.com/2021/10/09/C-emplace-back/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/C/">C++</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2021/11/10/%E7%90%86%E8%A7%A3C-%E8%99%9A%E5%87%BD%E6%95%B0%E8%A1%A8/"><i class="fa fa-chevron-left">  </i><span>理解C++虚函数表</span></a></div><div class="next-post pull-right"><a href="/2021/09/22/Rust%E7%9A%84Option%E7%9A%84%E6%AD%A3%E7%A1%AE%E6%89%93%E5%BC%80%E6%96%B9%E5%BC%8F/"><span>Rust的Option的正确打开方式</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2013 - 2022 By LiYang</div><div class="framework-info"><span>Driven - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>Theme - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script></body></html>